﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AddStrategyForm.cs" company="">
//   
// </copyright>
// <summary>
//   The add strategy form.
// </summary>
// --------------------------------------------------------------------------------------------------------------------


using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using Systemathics.FrameWork;

namespace Systemathics.UserControls
{
    public partial class AddStrategyForm : Form
    {
        private DBStrategies strat;
        public DBStrategies Strategy
        { 
            get
            {
                return strat;
            } 
            set
            {
                strat = value;
                UnBuildHourTextBox.Text = strat.UnBuildAt.Hours.ToString();
                UnBuildMinuteTextBox.Text = strat.UnBuildAt.Minutes.ToString();
                BuildHourTextBox.Text = strat.BuildAt.Hours.ToString();
                BuildMinuteTextBox.Text = strat.BuildAt.Minutes.ToString();
                CEtextBox.Text = strat.CashEquity.Value.ToString("C0", CultureInfo.CurrentCulture);
                MBtextBox.Text = (strat.MaxBias.Value * 100).ToString("N1");
                MDtextBox.Text = (strat.MaxDrawDown.Value * 100).ToString("N1");
                ///////////////////////checkedInstrumentsListBox.Items.AddRange(allDictionaryInstruments.TakeWhile(u => cell.Instruments.Contains(u.Key)).Select(u => u.Value.Name).ToArray());
                ///////////CheckAllChanged(sender, e);
                checkedInstrumentsListBox.Enabled = false;
                StrategyNameTextBox.Text = strat.Name;
                ParameterTagTextBox.Text = strat.Info;
                PatternComboBox.DataSource = new[] { strat.Pattern };
            } 
        }
        private readonly List<StaticData> allDictionaryInstruments;
        private double CashEquity;
        private bool GlobalCheck;
        private double MaxBias;
        private double MaxDrawDown;
        private TimeSpan UnBuildDateTime, BuidDateTime;
        private String InstrumentsFile;
        
        public bool TestSucceed = true;
        private Pattern[] patterns;
        public Pattern[] StrategiesPattern
        {
            get
            {
                return patterns;
            }
            set
            {
                patterns = value;
                foreach (var p in patterns)
                    PatternComboBox.Items.Add(p.PatternName);
                PatternComboBox.SelectedIndex = 0;
            }
        }

        public AddStrategyForm(Dictionary<Guid, StaticData> dico)
        {
            InitializeComponent();

            ShowIcon = false;
            MinimizeBox = false;
            MaximizeBox = false;
            checkedInstrumentsListBox.MultiColumn = true;
            allDictionaryInstruments = dico.Values.ToList();
            checkBox1.Enabled = false;
            strat = new DBStrategies();
            if (allDictionaryInstruments.Count == 0)
                Text = "No instrument in Dictionary !";

            var df = new DirectoryInfo(GlobalVariables.PARAMETERS);
            var xlsfiles = df.GetFiles("*.xls");
            var xlsxfiles = df.GetFiles("*.xlsx");

            foreach (var fileInfo in xlsxfiles)
                XlFilecomboBox.Items.Add(fileInfo.Name);
            foreach (var fileInfo in xlsfiles)
                XlFilecomboBox.Items.Add(fileInfo.Name);

            Thread.CurrentThread.CurrentCulture = GlobalVariables.SystemathicsCulture();
        }
       
        private void NewStrategyForm_Load(object sender, EventArgs e)
        {
            comboBox_Type.DataSource = Enum.GetValues(typeof (InstrumentType));
            comboBox_Class.DataSource = Enum.GetValues(typeof (AssetClass));
            comboBox_Sector.DataSource = Enum.GetValues(typeof (Sectors));

            comboBox_Type.SelectedItem = InstrumentType.Unknown;
            comboBox_Class.SelectedItem = AssetClass.Unknown;
            comboBox_Sector.SelectedItem = Sectors.Unknown;
        }

        private void SearchButton_Click(object sender, EventArgs e)
        {
            var p = new Predicate<StaticData>(SearchFunction);
            string[] arr = allDictionaryInstruments.ToList().FindAll(p).Select(u => u.Name).ToArray();
            Array.Sort(arr);
            foreach (var s in arr)
            {
                if (!checkedInstrumentsListBox.Items.Contains(s))
                    checkedInstrumentsListBox.Items.Add(s);
            }

            if (checkedInstrumentsListBox.Items.Count > 0)
                checkBox1.Enabled = true;
            Name = checkedInstrumentsListBox.Items.Count + " Instruments Found";
        }
        private bool SearchFunction(StaticData i)
        {
            if (i.Type == (InstrumentType) comboBox_Type.SelectedItem
                && i.Classe == (AssetClass) comboBox_Class.SelectedItem
                && i.Sector == (Sectors) comboBox_Sector.SelectedItem)
                return true;
            return false;
        }
        public void CheckAllChanged(object sender, EventArgs e)
        {
            if (checkedInstrumentsListBox.Items.Count > 0)
            {
                GlobalCheck = GlobalCheck ? false : true;
                for (int i = 0; i < checkedInstrumentsListBox.Items.Count; i++)
                    checkedInstrumentsListBox.SetItemChecked(i, GlobalCheck);
            }
        }
        private void Validate_Button_Click(object sender, EventArgs e)
        {
            StrategyNameTextBox_Validating(this, e);
            MDtextBoxValidating(this, e);
            MBtextBoxValidating(this, e);
            CEtextBoxValidating(this, e);
            BuidDateTime = new TimeSpan(int.Parse(BuildHourTextBox.Text), int.Parse(BuildMinuteTextBox.Text),0);
            UnBuildDateTime = new TimeSpan(int.Parse(UnBuildHourTextBox.Text), int.Parse(UnBuildMinuteTextBox.Text), 0);
            var u = checkedInstrumentsListBox.CheckedItems.Count;
            var strategyInstruments = new List<Guid>();
            if (PatternComboBox.SelectedItem == null || u == 0)
                TestSucceed = false;
            else
            {
                foreach (var item in checkedInstrumentsListBox.CheckedItems)
                    strategyInstruments.Add(allDictionaryInstruments.Where(h => h.Name == item.ToString()).FirstOrDefault().Id);
            }
            if(!String.IsNullOrEmpty(InstrumentsFile) && !String.IsNullOrEmpty(ParameterTagTextBox.Text))
            {
                var listofNames = new List<String>();
                TestSucceed = ProviderFactory.GetInstruments(InstrumentsFile, ParameterTagTextBox.Text, ref listofNames);
                strategyInstruments = allDictionaryInstruments.Where(h => listofNames.Contains(h.Name)).Select(z => z.Id).ToList();
            }

            if (TestSucceed)
            {
                using (var db = new SystemathicsEntities(GlobalVariables.EntitiesConnectionString()))
                {
                    if (strat.ID == Guid.Empty)
                    {
                        strat.ID = Guid.NewGuid();
                        strat = new DBStrategies
                                    {
                                        ID = strat.ID,
                                        CreationDate = DateTime.Now,
                                        Info = ParameterTagTextBox.Text,
                                        Name = StrategyNameTextBox.Text,
                                        Pattern = (String) PatternComboBox.SelectedItem,
                                        Version = StrategiesPattern.Where(g => g.PatternName == PatternComboBox.SelectedItem.ToString()).FirstOrDefault().Version,
                                        BuildAt = BuidDateTime,
                                        UnBuildAt = UnBuildDateTime,
                                        CashEquity = CashEquity,
                                        MaxBias = MaxBias/100,
                                        MaxDrawDown = MaxDrawDown/100
                                    };

                        foreach (var guid in strategyInstruments) 
                            strat.DBInstruments.Add(db.DBInstruments.Where(l => l.ID == guid).FirstOrDefault());
                    }
                    else
                    {
                        strat.Info = ParameterTagTextBox.Text;
                        strat.Name = StrategyNameTextBox.Text;
                        strat.Pattern = (String) PatternComboBox.SelectedItem;
                        strat.Version = StrategiesPattern.Where(g => g.PatternName == PatternComboBox.SelectedItem.ToString()).FirstOrDefault().Version;
                        strat.BuildAt = BuidDateTime;
                        strat.UnBuildAt = UnBuildDateTime;
                        strat.CashEquity = CashEquity;
                        strat.MaxBias = MaxBias/100;
                        strat.MaxDrawDown = MaxDrawDown/100;
                        //strat.DBInstruments.Load();
                    }
                    
                    //No Use to set all instruments strategy each time except when you create the strategy becaus ewhen you edit the strat Instruments combobox is disabled
                    //foreach (var t in strat.DBInstruments.Take(strat.DBInstruments.Count).ToArray()) strat.DBInstruments.Remove(t);
                    //foreach (var guid in strategyInstruments) strat.DBInstruments.Add(db.DBInstruments.Where(l => l.ID == guid).FirstOrDefault());

                    try
                    {
                        db.AddToDBStrategies(strat);
                    }
                    catch (Exception ex)
                    {
                    }
                    db.SaveChanges(true);
                    
                }
            }
            Close();
        }
        private void Clear_Button_Click(object sender, EventArgs e)
        {
            checkedInstrumentsListBox.Items.Clear();
            checkBox1.Enabled = false;
        }
        private void StrategyNameTextBox_Validating(object sender, EventArgs e)
        {
            if (StrategyNameTextBox.Text == string.Empty)
            {
                errorProvider1.SetError(StrategyNameTextBox, "Please enter a Name to this strategy");
                TestSucceed = false;
            }
            else
            {
                errorProvider1.SetError(StrategyNameTextBox, string.Empty);
                TestSucceed = TestSucceed & true;
            }
        }
        private void MDtextBoxValidating(object sender, EventArgs e)
        {
            if (double.TryParse(MDtextBox.Text, out MaxDrawDown))
            {
                errorProvider1.SetError(MDtextBox, string.Empty);
                TestSucceed = TestSucceed & true;
            }
            else if (Math.Abs(MaxDrawDown) > 100 || MaxDrawDown < 0)
            {
                errorProvider1.SetError(MDtextBox, "Please Check Max Draw Down Value");
                TestSucceed = false;
            }
            else
            {
                errorProvider1.SetError(MDtextBox, "Max Draw Down error");
                TestSucceed = false;
            }

        }
        private void MBtextBoxValidating(object sender, EventArgs e)
        {
            if (double.TryParse(MBtextBox.Text, out MaxBias))
            {
                errorProvider1.SetError(MBtextBox, string.Empty);
                TestSucceed = TestSucceed & true;
            }
            else if (Math.Abs(MaxBias) > 100 || MaxBias < 0)
            {
                errorProvider1.SetError(MBtextBox, "Please Check Max Bias Value");
                TestSucceed = false;
            }
            else
            {
                errorProvider1.SetError(MBtextBox, "Max Bias error");
                TestSucceed = false;
            }
        }
        private void CEtextBoxValidating(object sender, EventArgs e)
        {
            if (!double.TryParse(CEtextBox.Text,NumberStyles.Currency,CultureInfo.CurrentCulture, out CashEquity))
            {
                errorProvider1.SetError(CEtextBox, "Please Check Cash Equity");
                TestSucceed = false;
            }
            else if (CashEquity < 0)
            {
                errorProvider1.SetError(CEtextBox, "Please Check CashEquity Value");
                TestSucceed = false;
            }
            else
            {
                errorProvider1.SetError(CEtextBox, string.Empty);
                TestSucceed = TestSucceed & true;
            }
        }
        private void XlFilecomboBox_DropDownClosed(object sender, EventArgs e)
        {
            if (XlFilecomboBox.SelectedItem != null)
                InstrumentsFile = XlFilecomboBox.SelectedItem.ToString();
        }
    }
}
